<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <!--工具栏-->
      <div class="head-container">
        <div v-if="crud.props.searchToggle">
          <!-- 搜索 -->
          <el-input
            v-model="query.blurry"
            clearable
            size="small"
            placeholder="输入昵称"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="crud.toQuery"
          />
          <el-select
            v-model="query.deptId"
            clearable
            size="small"
            placeholder="部门"
            class="filter-item"
            style="width: 120px"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in optionsBm"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="query.enabled"
            clearable
            size="small"
            placeholder="状态"
            class="filter-item"
            style="width: 90px"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in enabledTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
          <rrOperation />
        </div>
        <crudOperation show="" :permission="permission">
          <el-button
            slot="right"
            v-permission="['admin','user:add']"
            :disabled="crud.selections.length === 0"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-refresh-left"
            @click="resetPwd(crud.selections)"
          >重置密码
          </el-button>
        </crudOperation>
      </div>
      <!--表单渲染-->
      <el-dialog
        append-to-body
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="600px"
      >
        <!-- 使用栅格系统规整表单布局 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form
              ref="form"
              :model="form"
              :rules="rules"
              size="small"
              label-width="80px"
              label-position="left"
            >
              <!-- 第一行：用户名和电话 -->
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item
                    label="用户名"
                    prop="username"
                    :rules="[
                      { required: true, message: '必填项不能为空', trigger: 'blur' },
                      {
                        pattern: /^[a-zA-Z0-9_]+$/,
                        message: '只能输入字母、数字和下划线',
                        trigger: 'blur'
                      },
                      {
                        min: 3,
                        max: 20,
                        message: '长度必须在3-20个字符之间',
                        trigger: 'blur'
                      }
                    ]"
                  >
                    <el-input
                      v-model="form.username"
                      style="width: 100%"
                      placeholder="请输入用户名"
                      @keydown.native="keydown($event)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电话" prop="phone">
                    <el-input
                      v-model.number="form.phone"
                      style="width: 100%"
                      placeholder="请输入电话号码"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第二行：昵称和邮箱 -->
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="昵称" prop="nickName">
                    <el-input
                      v-model="form.nickName"
                      style="width: 100%"
                      placeholder="请输入昵称"
                      @keydown.native="keydown($event)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input
                      v-model="form.email"
                      style="width: 100%"
                      placeholder="请输入邮箱地址"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第三行：部门和密码（仅新增时显示） -->
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="部门" prop="nodeDept">
                    <el-select
                      v-model="form.nodeDept"
                      placeholder="请选择申请部门"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in optionsBm"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col v-if="crud.status.add > 0" :span="12">
                  <el-form-item
                    label="密码"
                    prop="password"
                    :rules="[
                      { required: true, message: '必填项不能为空', trigger: 'blur' },
                      {
                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
                        message: '密码必须包含大小写字母、数字和特殊字符、不能少于8位',
                      }
                    ]"
                  >
                    <el-input
                      v-model="form.password"
                      type="password"
                      style="width: 100%"
                      placeholder="请设置密码"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第四行：性别和状态 -->
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="性别">
                    <el-radio-group v-model="form.gender" style="width: 100%">
                      <el-radio label="男" style="margin-right: 20px">男</el-radio>
                      <el-radio label="女">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态">
                    <el-radio-group
                      v-model="form.enabled"
                      :disabled="form.id === user.id"
                      style="width: 100%"
                    >
                      <el-radio
                        v-for="item in dict.user_status"
                        :key="item.id"
                        :label="item.value"
                        style="margin-right: 15px"
                      >{{ item.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第五行：角色选择 -->
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label="角色"
                    prop="roleDatas"
                    class="is-required"
                  >
                    <el-select
                      v-model="roleDatas"
                      :disabled="form.id === user.id"
                      style="width: 100%"
                      multiple
                      placeholder="请选择角色"
                      @remove-tag="deleteTag"
                      @change="changeRole"
                    >
                      <el-option
                        v-for="item in roles"
                        :key="item.name"
                        :disabled="level !== 1 && item.level <= level"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
        </el-row>

        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <!--修改密码对话框-->
      <el-dialog append-to-body title="修改密码" :visible.sync="showPasswordDialog" width="400px">
        <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="80px">
          <el-form-item label="旧密码" prop="newPassword">
            <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入新密码" />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordChange">确认</el-button>
        </div>
      </el-dialog>

      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column :selectable="checkboxT" type="selection" />
        <el-table-column :show-overflow-tooltip="true" prop="username" label="用户名" width="300" />
        <el-table-column :show-overflow-tooltip="true" prop="nickName" label="昵称" />
        <el-table-column prop="gender" label="性别" />
        <el-table-column :show-overflow-tooltip="true" prop="phone" label="电话" />
        <el-table-column :show-overflow-tooltip="true" prop="email" label="邮箱" />
        <el-table-column :show-overflow-tooltip="true" prop="dept" label="部门">
          <template slot-scope="scope">
            <div>{{ scope.row.userDept ? scope.row.userDept.name : '未分配部门' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="enabled">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              :disabled="user.id === scope.row.id"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.enabled)"
            />
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建日期" />
        <el-table-column
          v-if="checkPer(['admin','user:edit','user:del'])"
          label="操作"
          width="200"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-permission="['admin','user:edit']"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="crud.toEdit(scope.row)"
            >编辑
            </el-button>
            <el-button
              v-permission="['admin','user:edit']"
              size="mini"
              type="text"
              icon="el-icon-key"
              @click="openPasswordDialog(scope.row)"
            >改密
            </el-button>
            <el-button
              v-permission="['admin','user:del']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              :disabled="scope.row.id === user.id"
              @click="handleSingleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </el-row>
  </div>
</template>

<script>
import { encrypt } from '@/utils/rsaEncrypt'
import crudUser from '@/api/system/user'
import { isvalidPhone } from '@/utils/validate'
import { getDepts, getDeptSuperior, updatePass } from '@/api/system/dept'
import { getAll, getLevel } from '@/api/system/role'
import { getAllJob } from '@/api/system/job'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
// import DateRangePicker from '@/components/DateRangePicker'
import { mapGetters } from 'vuex'

let userRoles = []
let userJobs = []
const defaultForm = {
  id: null,
  username: null,
  nickName: null,
  gender: '男',
  email: null,
  enabled: 'false',
  roles: [],
  jobs: [],
  dept: { id: null },
  phone: null,
  password: null,
  nodeDept: null
}

export default {
  name: 'User',
  components: { crudOperation, rrOperation, pagination },
  cruds() {
    return CRUD({ title: '用户', url: 'api/users', crudMethod: { ...crudUser }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status'],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }

    // 密码验证
    const validatePassword = (rule, value, callback) => {
      if (!value && this.crud.status.add > 0) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }

    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      level: null,
      roles: [],
      optionsBm: [],
      height: document.documentElement.clientHeight - 180 + 'px;',
      jobDatas: [], roleDatas: [], // 多选时使用
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '激活' },
        { key: 'false', display_name: '锁定' }
      ],
      showPasswordDialog: false,
      passwordForm: {
        userId: null,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        newPassword: [
          { required: true, validator: validatePassword, trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        'dept.id': [
          { required: true, message: '部门不能为空', trigger: 'blur' }
        ],
        roleDatas: [
          {
            validator: (rule, value, callback) => {
              value = this.roleDatas
              if (!value || value.length === 0) {
                callback(new Error('请选择至少一个角色'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        nodeDept: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.crud.msg.add = '新增成功'
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
    this.getDepts()
  },
  methods: {
    handleSingleDelete(row) {
      // 与批量删除逻辑一致：弹出确认框 → 调用 doDelete
      this.$confirm(`确定删除用户「${row.username}」?`, '提示', {
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true // 显示加载状态
        this.crud.doDelete([row]) // 转为数组，适配批量删除接口
      }).catch(() => {
        // 用户取消，不操作
      })
    },
    // 禁止输入空格
    keydown(e) {
      if (e.keyCode === 32) {
        e.returnValue = false
      }
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function(data, index) {
        const role = { id: data }
        userRoles.push(role)
      })
    },
    changeJob(value) {
      userJobs = []
      value.forEach(function(data, index) {
        const job = { id: data }
        userJobs.push(job)
      })
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data.id === value) {
          // userRoles.splice(index, value)
          userRoles.splice(index, 1)
        }
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles()
      if (form.id == null) {
        this.getDepts()
      } else {
        // this.getSupDepts(form.dept.id)
      }
      this.getRoleLevel()
      this.getJobs()
      form.enabled = form.enabled.toString()
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.jobDatas = []
      this.roleDatas = []
    },
    // 初始化编辑时候的角色与岗位
    [CRUD.HOOK.beforeToEdit](crud, form) {
      // 先获取部门数据
      this.getDepts()
      this.getJobs(this.form.dept.id)
      this.jobDatas = []
      this.roleDatas = []
      userRoles = []
      userJobs = []
      const _this = this
      form.roles.forEach(function(role, index) {
        _this.roleDatas.push(role.id)
        const rol = { id: role.id }
        userRoles.push(rol)
      })
      form.jobs.forEach(function(job, index) {
        _this.jobDatas.push(job.id)
        const data = { id: job.id }
        userJobs.push(data)
      })
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      // 如果是新增用户，对密码进行加密
      if (crud.status.add > 0 && crud.form.password) {
        crud.form.password = encrypt(crud.form.password)
      }

      crud.form.roles = userRoles
      crud.form.jobs = userJobs
      return true
    },
    getDepts() {
      getDepts().then(res => {
        this.optionsBm = res
      })
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
        this.optionsBm = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.user_status[val] + '" ' + data.username + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudUser.edit(data).then(res => {
          this.crud.notify(this.dict.label.user_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => {
      })
    },
    // 获取弹窗内岗位数据
    getJobs() {
      getAllJob().then(res => {
        this.jobs = res.content
      }).catch(() => {
      })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => {
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    },
    resetPwd(datas) {
      this.$confirm(`你选中了 ${datas.length} 位用户，确认重置用户的密码吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        datas.forEach(val => {
          ids.push(val.id)
        })
        crudUser.resetPwd(ids).then(() => {
          this.crud.notify('重置成功, 用户新密码:123456', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.toQuery()
        }).catch(() => {
        })
      }).catch(() => {
      })
    },
    // 打开修改密码对话框
    openPasswordDialog(user) {
      // this.passwordForm.oldPassword = user.password
      this.passwordForm.userId = user.id
      this.passwordForm.newPassword = ''
      this.passwordForm.confirmPassword = ''
      this.showPasswordDialog = true
      this.$nextTick(() => {
        this.$refs.passwordForm.clearValidate()
      })
    },
    // 提交密码修改
    submitPasswordChange() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          const encryptedPassword = encrypt(this.passwordForm.newPassword)
          const encryptOldPassword = encrypt(this.passwordForm.oldPassword)
          updatePass({
            id: this.passwordForm.userId,
            oldPass: encryptOldPassword,
            newPass: encryptedPassword
          }).then(() => {
            this.showPasswordDialog = false
            this.crud.notify('密码修改成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          }).catch(() => {
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  ::v-deep .el-table {
    padding: 0 4px;
    box-sizing: border-box;

    .el-table__cell {
      padding: 8px 0;
    }

    .cell {
      padding: 0 8px;
    }
  }

  .head-container {
    //margin-bottom: 15px;
  }
}
</style>
